package com.longbo.leaf.aop;

import com.alibaba.fastjson.JSON;
import com.longbo.leaf.portal.model.Syslog;
import com.longbo.leaf.portal.service.ISyslogService;
import com.longbo.leaf.vo.UserPrincipal;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 自定义操作日志切面处理类
 */
@Slf4j
@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private ISyslogService syslogService;

    @Pointcut("@annotation(com.longbo.leaf.aop.MyLog)")
    public void logPointCut(){

    }

    //切面 配置通知
    @AfterReturning("logPointCut()")
    public void saveSysLog(JoinPoint joinPoint){
        System.out.println("切面....");

        //保存日志
        Syslog syslog = new Syslog();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        //获取操作
        MyLog myLog = method.getAnnotation(MyLog.class);
        if(null!=myLog){
            String value = myLog.value();
            syslog.setOperation(value);    //保存获取的操作
        }

        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取请求的方法名
        String methodName = method.getName();
        syslog.setMethod(className+"."+methodName);    //保存操作的方法

        //请求参数
        Object[] args = joinPoint.getArgs();

        //将请求参数所在数组转换成json字符串
        String params = JSON.toJSONString(args);
        syslog.setParams(params);

        //获取用户名
        UserPrincipal user = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = user.getUsername();
        syslog.setUsername(username);

        //当前时间
        LocalDateTime now = LocalDateTime.now();
        syslog.setCreatedate(now);

        //获取用户地址   注意:具体不知怎么获取
        syslog.setIp("localhost");

        //调用Service保存Syslog实体类到数据库
        syslogService.saveSysLog(syslog);
    }

}
